import json,requests
import os
import time

from bs4 import BeautifulSoup


class Movies():
    def __init__(self,i):
        self.url = f'https://spa3.scrape.center/api/movie/?limit=10&offset={i}'
        self.comment_url = f'https://spa3.scrape.center/api/movie/'
        self.headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}

    def send_re(self,url):
        response = requests.get(url, headers=self.headers)
        return response

    def send_img(self,url):
        response = requests.get(url, headers=self.headers)
        return response


    def jiexi(self,result,page):
        result_json = result.json()
        # 定位“电影”区域（根据网页结构，可能需要更新）

        movies = []

        # 遍历每部电影卡片
        for item in result_json.get('results'):
            title_name = item.get('name')
            title_alias = item.get('alias')
            title_cover = item.get('cover')
            title_categories = item.get('categories')
            comment = item.get('drama')



            img_result = self.send_img(title_cover)

            with open(f'./img/{title_name}.jpg','wb') as f:
                f.write(img_result.content)
                print(f'已保存{title_name}')

            if title_name:
                movies.append({
                    'page_title': f'第{page}页',
                    'title': title_name,
                    'title_alias': title_alias,
                    'title_cover': title_cover,
                    'title_categories': title_categories,
                    'comment': comment
                })



        return movies

if __name__ == '__main__':
    for i in range(0,5):
    #     print(i)
        m = Movies(i*10)
        result = m.send_re(m.url)
        aa = m.jiexi(result,i)
        print(f'第{i}页结束')
        # 1. 读旧数据（若文件不存在则初始化为 []）
        if os.path.exists('result.json'):
            with open('result.json', 'r', encoding='utf-8') as f:
                data = json.load(f)
        else:
            data = []

        if isinstance(data, list):
            data.extend(aa)
        else:
            data.append(aa)

        with open('result.json', 'w+', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
        time.sleep(1)


